const express = require('express')
const router = express.Router()
const KeyWord = require('../models/KeyWord')
const Feed = require('../models/Feed')

router.get('/', async (req, res) => {
  const { word, start = 0 } = req.query
  if (word.trim().length) {
    if (Number(start) === 0) {
      await KeyWord.findOneAndUpdate(
        { name: word },
        { $inc: { click: 1 } },
        { upsert: true, new: true },
      )
    }

    Feed.find({ title: { $regex: word } }, { _id: 0, __v: 0 })
      .count()
      .then(total => {
        Feed.find({ title: { $regex: word } }, { _id: 0, __v: 0 })
          .skip(start)
          .limit(10)
          .then(data => {
            res.json({
              code: 200,
              data: {
                list: data,
                nextIndex: Number(start) + 10,
                total,
                isEnd: Number(start) + 10 > total,
              },
            })
          })
      })
  }
})

/**
 * 获取前12个热词
 */
router.get('/hotwords', (req, res) => {
  KeyWord.find({}, '_id name')
    .limit(12)
    .sort('-click')
    .then(data => {
      res.json({
        code: 200,
        data: {
          hotwords: data,
        },
      })
    })
})

/**
 * 建议提示
 */
router.get('/suggest', (req, res) => {
  const { word } = req.query
  KeyWord.find({ name: { $regex: word } }, '_id name')
    .limit(10)
    .then(data => {
      res.json({
        code: 200,
        data: {
          list: data,
        },
      })
    })
})

module.exports = router
